package org.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.example.common.BaseResponse;
import org.example.common.ErrorCode;
import org.example.common.ResultUtils;
import org.example.exception.BusinessException;
import org.example.model.User;
import org.example.model.domain.UserLoginRequest;
import org.example.model.domain.UserRegisterRequest;
import org.example.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static org.example.constant.UserConstant.ADMIN_ROLE;
import static org.example.constant.UserConstant.USER_LOGIN_STATE;


@RestController
@RequestMapping("/user")
@CrossOrigin(origins = {"http://111.230.111.143:8080",
        "http://111.230.111.143","http://localhost:8080","http://localhost:8001"},allowCredentials = "true")
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 用户注册
     *
     * @param userRegisterRequest 用户注册请求
     * @return {@link Long}
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
      if(userRegisterRequest==null){
          throw new BusinessException(ErrorCode.PARAMS_ERROR);
      }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();

        if(StringUtils.isAnyEmpty(userAccount,userPassword,checkPassword,planetCode)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long l = userService.userRegister(userAccount, userPassword, checkPassword, planetCode);
        return ResultUtils.success(l);
    }

    /**
     * 用户登录
     *
     * @param userRegisterRequest 用户
     * @param request             请求
     * @return {@link User}
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userRegisterRequest, HttpServletRequest request){
        if(userRegisterRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        if(StringUtils.isAnyEmpty(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     *
     * @param request             请求
     * @return {@link User}
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request){
        if(request==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        int i = userService.userLogout(request);
        return ResultUtils.success(i);
    }

    /**
     * 当前用户
     *
     * @param request 请求
     * @return {@link User}
     */
    @GetMapping("/current")
    public BaseResponse<User> currentUser(HttpServletRequest request){
        User currentUser= (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if(currentUser==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        //todo 检验用户是否合法
        Long id = currentUser.getId();
        User user = userService.getById(id);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }

    /**
     * 搜索
     *
     * @param username 用户名
     * @param request  请求
     * @return {@link List}<{@link User}>
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username,HttpServletRequest request){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if(!isAdmin(request)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if(StringUtils.isNotBlank(username)){
            userQueryWrapper.like("username",username);
        }
        List<User> usersList = userService.list(userQueryWrapper);
        List<User> collect = usersList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(collect);
    }

    /**
     * 删除
     *
     * @param id id
     * @return boolean
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean>  delete(@RequestBody  long id,HttpServletRequest request){
          if(!isAdmin(request)){
              throw new BusinessException(ErrorCode.NOT_AUTH);
          }
        if(id<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(id);;
        return ResultUtils.success(b);
    }

    /**
     * 是否为管理
     *
     * @param request 请求
     * @return boolean
     */
    private boolean isAdmin(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        return user == null || user.getUserRole() != ADMIN_ROLE;
    }

    @GetMapping("/check")
    public BaseResponse<List<User>> check(){
        List<User> list = userService.list();
        List<User> collect = list.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        System.out.println("10001");
        return ResultUtils.success(collect);
    }
}
